package go_prometheus_basic_data

import (
	"errors"
	"github.com/prometheus/client_golang/prometheus"
	"runtime"
)

// 程序基础信息统计
var (
	memAlloc = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "mem_alloc",
		Help: "堆空间分配的字节数",
	})
	memSys = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "mem_sys",
		Help: "从系统获取到的总内存",
	})
	memHeapIdle = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "mem_heap_idle",
		Help: "堆空闲(申请未使用)",
	})
	memHeapInuse = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "mem_heap_inuse",
		Help: "使用中堆内存",
	})
	memStackSys = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "mem_stack_sys",
		Help: "系统分配作为运行栈的内存",
	})
	memStackInuse = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "mem_stack_inuse",
		Help: "正在使用栈内存",
	})
	memActiveObjects = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "mem_active_object",
		Help: "活跃的对象",
	})
	sysUseCpu = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "sys_use_cpu",
		Help: "cpu使用情况平均值",
	})
	sysUseRam = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "sys_use_ram",
		Help: "内存使用情况平均值",
	})
	sysUseDisk = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "sys_use_disk",
		Help: "磁盘使用情况平均值",
	})
)

func MustRegister() {
	prometheus.MustRegister(memAlloc, memSys, memHeapIdle, memHeapInuse, memStackSys, memStackInuse,
		memActiveObjects, sysUseCpu, sysUseRam, sysUseDisk)
}

func Update() error {
	var (
		err       error
		c         Cpu
		r         Ram
		d         Disk
		errString string
	)
	ms := new(runtime.MemStats)
	runtime.ReadMemStats(ms)
	memAlloc.Set(float64(ms.Alloc / MB))
	memSys.Set(float64(ms.Sys / MB))
	memHeapIdle.Set(float64(ms.HeapIdle / MB))
	memHeapInuse.Set(float64(ms.HeapInuse / MB))
	memStackSys.Set(float64(ms.StackSys / MB))
	memStackInuse.Set(float64(ms.StackInuse / MB))
	memActiveObjects.Set(float64(ms.Mallocs - ms.Frees))
	// 获取cpu情况
	c, err = GetCPU()
	if err != nil {
		errString += "获取cpu结果失败(" + err.Error() + ");"
	}
	sysUseCpu.Set(c.UsedPercent)
	// 获取机器内存信息
	r, err = GetRAM()
	if err != nil {
		errString += "获取机器内存信息失败(" + err.Error() + ");"
	}
	sysUseRam.Set(r.UsedPercent)
	// 获取机器磁盘信息
	d, err = GetDisk()
	if err != nil {
		errString += "获取机器磁盘信息失败(" + err.Error() + ");"
	}
	sysUseDisk.Set(d.UsedPercent)
	if errString != "" {
		return errors.New(errString)
	}
	return nil
}
